#include "MQTTClient.h"
#include <stdio.h>
#include <string.h>
#include <unistd.h>   // sleep()

// #define MQTT_BROKER "192.168.155.228"  // Windows 局域网 IP
#define MQTT_BROKER "broker.emqx.io"  // Windows 局域网 IP
#define MQTT_PORT   1883
#define MQTT_CLIENT_ID "demo_client"
#define MQTT_TOPIC "qqq"

int MQTTTask(void)
{
    int rc;
    Network network;
    MQTTClient client;
    unsigned char sendbuf[100], readbuf[100];

    // 1. 初始化网络
    NetworkInit(&network);
    rc = NetworkConnect(&network, MQTT_BROKER, MQTT_PORT);
    if (rc != 0) {
        printf("NetworkConnect failed: %d\n", rc);
        return -1;
    }
    printf("NetworkConnect success\n");

    // 2. 初始化客户端
    MQTTClientInit(&client, &network, 1000, sendbuf, sizeof(sendbuf), readbuf, sizeof(readbuf));

    printf(__FILE__ ":%d\n", __LINE__);
    // 3. 设置连接参数
    MQTTPacket_connectData connectData = MQTTPacket_connectData_initializer;
    connectData.MQTTVersion = 4;
    connectData.clientID.cstring = MQTT_CLIENT_ID;
    connectData.keepAliveInterval = 10;
    connectData.cleansession = 1;

    printf(__FILE__ ":%d\n", __LINE__);
    // 4. 连接服务器
    rc = MQTTConnect(&client, &connectData);
    if (rc != 0) {
        printf("MQTTConnect failed: %d\n", rc);
        NetworkDisconnect(&network);
        return -1;
    }
    printf("Connected to MQTT broker!\n");

    // 5. 发送一条消息
    MQTTMessage message;
    const char* payload = "Hello from board!";
    message.qos = QOS0;
    message.retained = 0;
    message.dup = 0;
    message.payload = (void*)payload;
    message.payloadlen = strlen(payload);

    rc = MQTTPublish(&client, MQTT_TOPIC, &message);
    if (rc != 0) {
        printf("MQTTPublish failed: %d\n", rc);
    } else {
        printf("Message sent: %s\n", payload);
    }

    // 6. 断开连接
    MQTTDisconnect(&client);
    NetworkDisconnect(&network);
    printf("Disconnected.\n");

    return 0;
}

static void MQTTTaskEntry(void)
{
    /** 任务属性的结构体 **/
    osThreadAttr_t attr;

    attr.name = "MQTTTask";         //任务名称
    attr.attr_bits = 0U;            //任务的属性位
    attr.cb_mem = NULL;             //任务控制块的内存初始地址，默认为系统自动分配
    attr.cb_size = 0U;              //任务控制块的内存大小
    attr.stack_mem = NULL;          //任务的内存初始地址，默认为系统自动分配
    attr.stack_size = 8192;         //任务的内存大小
    attr.priority = 30;             //任务的优先级

	sleep(10);
    /** 创建任务 **/
    if (osThreadNew((osThreadFunc_t)MQTTTask, NULL, &attr) == NULL) {
        printf("[PWMTaskEntry] Falied to create MQTTTask!\n");
    }
}


SYS_RUN(MQTTTaskEntry);